from fastapi import APIRouter, status, Query, Depends, HTTPException
from typing import Optional
from app.modules.permissions.models import PermissionModel
from app.modules.permissions.schemas import (
    PermissionCreateInput, PermissionCreatedResponse, PermissionUpdate, 
    PermissionInfo, PermissionListResponse, PermissionTreeResponse,
    PermissionBatchUpdate, PermissionQueryParams
)
from app.modules.permissions.services import PermissionService
from app.core.responses import success_response, error_response
from app.core.exceptions import BusinessException
from app.core.dependencies import get_current_user
from app.modules.users.models import UserModel

router = APIRouter(
    prefix="/api/permissions", 
    tags=["权限管理"],
    dependencies=[Depends(get_current_user)]
)


@router.post("/", summary="创建权限", response_model=PermissionCreatedResponse)
async def create_permission(
    permission_in: PermissionCreateInput, 
    current_user: UserModel = Depends(get_current_user)
):
    """
    创建新权限
    
    - **name**: 权限名称
    - **code**: 权限编码（唯一）
    - **type**: 权限类型（menu/button/api）
    - **parent_id**: 父级权限ID（0表示根级权限）
    - **path**: 路由路径（菜单权限）
    - **component**: 组件路径（菜单权限）
    - **icon**: 图标（菜单权限）
    - **sort_order**: 排序
    - **is_visible**: 是否可见
    - **is_active**: 是否激活
    - **remark**: 备注
    """
    result = await PermissionService.create_permission(permission_in)
    return success_response(
        data=result,
        message="权限创建成功",
        code=status.HTTP_201_CREATED
    )


@router.get("/", summary="获取权限列表", response_model=PermissionListResponse)
async def get_permission_list(
    page: int = Query(1, ge=1, description="页码"),
    size: int = Query(10, ge=1, le=100, description="每页数量"),
    name: Optional[str] = Query(None, description="权限名称"),
    code: Optional[str] = Query(None, description="权限编码"),
    type: Optional[str] = Query(None, description="权限类型"),
    parent_id: Optional[int] = Query(None, description="父级权限ID"),
    is_active: Optional[bool] = Query(None, description="是否激活"),
    is_visible: Optional[bool] = Query(None, description="是否可见"),
    is_system: Optional[bool] = Query(None, description="是否系统权限")
):
    """获取权限分页列表，支持多种查询条件"""
    query_params = PermissionQueryParams(
        name=name,
        code=code,
        type=type,
        parent_id=parent_id,
        is_active=is_active,
        is_visible=is_visible,
        is_system=is_system
    )
    
    total, items = await PermissionService.get_permission_list(
        skip=(page - 1) * size, 
        limit=size,
        query_params=query_params
    )
    return success_response(data={"total": total, "items": items})


@router.get("/tree", summary="获取权限树", response_model=PermissionTreeResponse)
async def get_permission_tree():
    """获取权限树结构，用于前端菜单展示"""
    tree = await PermissionService.get_permission_tree()
    return success_response(data={"items": tree})


@router.get("/menus", summary="获取菜单权限")
async def get_menus():
    """获取所有菜单权限"""
    menus = await PermissionService.get_menus()
    return success_response(data=menus)


@router.get("/buttons", summary="获取按钮权限")
async def get_buttons():
    """获取所有按钮权限"""
    buttons = await PermissionService.get_buttons()
    return success_response(data=buttons)


@router.get("/apis", summary="获取接口权限")
async def get_apis():
    """获取所有接口权限"""
    apis = await PermissionService.get_apis()
    return success_response(data=apis)


@router.get("/root", summary="获取根级权限")
async def get_root_permissions():
    """获取根级权限（parent_id=0）"""
    permissions = await PermissionService.get_root_permissions()
    return success_response(data=permissions)


@router.get("/{permission_id}", summary="获取权限详情", response_model=PermissionInfo)
async def get_permission_detail(permission_id: int):
    """根据权限ID获取权限详情"""
    permission = await PermissionService.get_by_id(permission_id)
    return success_response(data=PermissionInfo.from_orm(permission))


@router.get("/{permission_id}/children", summary="获取权限子权限")
async def get_permission_children(permission_id: int):
    """获取指定权限的子权限列表"""
    children = await PermissionService.get_permission_children(permission_id)
    return success_response(data=children)


@router.get("/{permission_id}/ancestors", summary="获取权限祖先权限")
async def get_permission_ancestors(permission_id: int):
    """获取指定权限的祖先权限列表"""
    ancestors = await PermissionService.get_permission_ancestors(permission_id)
    return success_response(data=ancestors)


@router.get("/{permission_id}/descendants", summary="获取权限后代权限")
async def get_permission_descendants(permission_id: int):
    """获取指定权限的后代权限列表"""
    descendants = await PermissionService.get_permission_descendants(permission_id)
    return success_response(data=descendants)


@router.patch("/{permission_id}", summary="更新权限信息", response_model=PermissionInfo)
async def update_permission(
    permission_id: int, 
    permission_in: PermissionUpdate,
    current_user: UserModel = Depends(get_current_user)
):
    """
    更新权限信息
    
    - 系统权限不允许修改
    - 权限编码不能重复
    - 父级权限必须存在
    """
    result = await PermissionService.update_permission(permission_id, permission_in)
    return success_response(data=result, message="权限更新成功")


@router.delete("/{permission_id}", summary="删除权限")
async def delete_permission(
    permission_id: int,
    current_user: UserModel = Depends(get_current_user)
):
    """
    删除权限
    
    - 系统权限不允许删除
    - 存在子权限时无法删除
    - 有角色使用时无法删除
    """
    await PermissionService.delete_permission(permission_id)
    return success_response(message="权限删除成功")


@router.patch("/batch", summary="批量更新权限")
async def batch_update_permissions(
    batch_data: PermissionBatchUpdate,
    current_user: UserModel = Depends(get_current_user)
):
    """
    批量更新权限状态
    
    - 系统权限不允许批量修改
    - 支持批量更新激活状态和可见性
    """
    update_data = batch_data.dict(exclude_unset=True, exclude={'ids'})
    if not update_data:
        raise BusinessException(message="没有要更新的数据")
    
    await PermissionService.batch_update_permissions(batch_data.ids, update_data)
    return success_response(message="批量更新成功")


@router.post("/batch/codes", summary="根据编码获取权限")
async def get_permissions_by_codes(codes: list[str]):
    """根据权限编码列表获取权限信息"""
    permissions = await PermissionService.get_permissions_by_codes(codes)
    return success_response(data=permissions)


@router.get("/check/{permission_code}", summary="检查权限编码是否存在")
async def check_permission_code(permission_code: str):
    """检查权限编码是否已存在"""
    permission = await PermissionService.get_by_code(permission_code)
    exists = permission is not None
    return success_response(data={"exists": exists, "permission": PermissionInfo.from_orm(permission) if permission else None})
